<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { reqQrcode, reqQueryPayState } from '@/api/user.ts'
//生成二维码插件qrcode
import QRCode from "qrcode"
const router = useRouter()
const dialogFormVisible = ref(false)
const changeDialogFormVisible = (flag: boolean) => {
    dialogFormVisible.value = flag
}

const codeUrl = ref('')
const getReqQrcode = async () => {
    const res = await reqQrcode(router.currentRoute.value.query.orderId as string)
    // console.log(res.data.codeUrl)
    // 拿到后借用插件生成二维码显示
    codeUrl.value = await QRCode.toDataURL(res.data.codeUrl);
}

watch(dialogFormVisible, (newVal) => {
    let timer
    if (newVal) {
        getReqQrcode()
        timer = setInterval(async () => {
            // getReqQrcode()
            // 不断请求订单状态
            await reqQueryPayState(router.currentRoute.value.query.orderId as string)
        }, 5000)
    } else {
        clearInterval(timer)
    }
})

defineExpose({   //暴露出去的方法
    changeDialogFormVisible
})
</script>

<template>
    <el-dialog v-model="dialogFormVisible" title="微信支付" width="300">
        <img :src="codeUrl" alt="">
        <p>请使用微信扫描二维码完成支付</p>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="changeDialogFormVisible(false)">
                    关闭窗口
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped></style>